﻿using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using CCTool.Scripts.Manager;
using CCTool.Scripts.MapMenu;
using CCTool.Scripts.ToolManagers.Managers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CCTool.Scripts.ToolManagers.Library;
using ArcGIS.Desktop.Internal.GeoProcessing.Controls;
using ArcGIS.Desktop.Internal.Core;

namespace CCTool.Scripts.Lab
{
    /// <summary>
    /// Interaction logic for DownloadLab.xaml
    /// </summary>
    public partial class DownloadLab : ArcGIS.Desktop.Framework.Controls.ProWindow
    {
        public DownloadLab()
        {
            InitializeComponent();


            try
            {
                // 绑定TreeView数据
                this.tv.DataContext = MapItems.getData();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                return;
            }

        }

        private void tv_Load(object sender, RoutedEventArgs e)
        {
            try
            {
                // 递归展开所有TreeViewItem的方法
                ExpandAllTreeViewItems(tv);
                // 隐藏非子节点的按钮
                HideButtonsForNonChildNodes(tv);

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                return;
            }

        }

        // 递归展开所有TreeViewItem的方法
        private void ExpandAllTreeViewItems(ItemsControl itemsControl)
        {
            foreach (var item in itemsControl.Items)
            {
                var treeViewItem = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                if (treeViewItem != null)
                {
                    treeViewItem.IsExpanded = true;

                    // 如果这个节点还有子节点，递归展开
                    if (treeViewItem.Items.Count > 0)
                    {
                        ExpandAllTreeViewItems(treeViewItem);
                    }
                }
            }

            // 确保第一级节点展开（有时需要这个额外的步骤）
            itemsControl.UpdateLayout();
            foreach (var item in itemsControl.Items)
            {
                var treeViewItem = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                if (treeViewItem != null)
                {
                    treeViewItem.IsExpanded = true;
                }
            }
        }

        // 隐藏非子节点的按钮
        private void HideButtonsForNonChildNodes(ItemsControl itemsControl)
        {
            foreach (var item in itemsControl.Items)
            {
                var treeViewItem = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                if (treeViewItem != null)
                {
                    // 递归查找StackPanel（解决模板层级问题）
                    var stackPanel = FindVisualChild<StackPanel>(treeViewItem);
                    if (stackPanel != null && stackPanel.Orientation == Orientation.Horizontal)
                    {
                        var button = stackPanel.Children.OfType<Button>().FirstOrDefault();
                        if (button != null)
                        {
                            button.Visibility = treeViewItem.HasItems ?
                                Visibility.Collapsed :
                                Visibility.Visible;
                        }
                    }

                    // 递归处理子节点
                    if (treeViewItem.HasItems)
                    {
                        HideButtonsForNonChildNodes(treeViewItem);
                    }
                }
            }
        }


        // 通用的视觉树查找方法（解决层级不确定问题）[3](@ref)[5](@ref)[6](@ref)
        private static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            if (parent == null) return null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T found)
                    return found;

                var result = FindVisualChild<T>(child);
                if (result != null)
                    return result;
            }
            return null;
        }

        private void btn_link_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            StackPanel p = (StackPanel)btn.GetParentObject();
            if (p != null)
            {
                string content = p.GetChildOfType<TextBlock>().Text;

                // 集合
                Dictionary<string, string> dict = MapItems.ccToolDict
                    .Union(MapItems.softDict).ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
                    .Union(MapItems.sdkDict).ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
                    .Union(MapItems.dataDict).ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
                    ;

                // 连接
                UITool.Link2Web(dict[content]);

            }

        }


    }




    public class MapItem
    {
        public string MapName { get; set; }

        public MapItems mapItems { get; set; }

        public void SetMapValue(List<string> mapNames)
        {
            this.mapItems = new MapItems();

            foreach (string mapName in mapNames)
            {
                this.mapItems.Add(new MapItem() { MapName = mapName});
            }
        }
    }

    public class MapItems : ObservableCollection<MapItem>
    {
        public static MapItems getData()
        {
            MapItems mapItems = new MapItems();

            // CC工具箱相关
            MapItem mapItem = new MapItem() { MapName = "CC工具箱相关"};
            List<string> mapNames = ccToolDict.Keys.ToList();
            mapItem.SetMapValue(mapNames);
            mapItems.Add(mapItem);

            // CC工具箱相关
            mapItem = new MapItem() { MapName = "ArcGIS Pro SDK二次开发" };
            mapNames = sdkDict.Keys.ToList();
            mapItem.SetMapValue(mapNames);
            mapItems.Add(mapItem);

            // 数据资源
            mapItem = new MapItem() { MapName = "数据资源" };
            mapNames = dataDict.Keys.ToList();
            mapItem.SetMapValue(mapNames);
            mapItems.Add(mapItem);

            // 软件安装包
            mapItem = new MapItem() { MapName = "软件安装包" };
            mapNames = softDict.Keys.ToList();
            mapItem.SetMapValue(mapNames);
            mapItems.Add(mapItem);

            return mapItems;
        }

        #region

        // CC工具箱相关
        public static Dictionary<string, string> ccToolDict = new Dictionary<string, string>()
        {
            { "CC工具箱最新版本", "https://pan.baidu.com/s/1OJmO6IPtMfX_vob3bMtvEg?pwd=uh5r"},
            { "CC工具箱C#原码", "https://pan.baidu.com/s/1teO_MeGPDRy4rAp-z-3sIw?pwd=2qub"},
        };

        // ArcGIS Pro SDK二次开发
        public static Dictionary<string, string> sdkDict = new Dictionary<string, string>()
        {
            { "ArcGIS Pro SDK3.4安装包", "https://pan.baidu.com/s/1Ym_C9NsRvK0aKmTOzAT2Mg?pwd=16eb"},
            { "ArcGIS Pro API Reference本地文档", "https://pan.baidu.com/s/1LL9f9X_PNH4hcO2akahTCQ?pwd=isk5"},
        };

        // 数据资源
        public static Dictionary<string, string> dataDict = new Dictionary<string, string>()
        {
            { "常用stylx样式库(二调、三调、国空、乱七八糟)", "https://pan.baidu.com/s/1_TkXZ2AHlakTBRNtPx6Z0Q?pwd=srnt"},
            { "在线影像lyrx", "https://pan.baidu.com/s/1nygwzpKGkpRXanH5j-eKrg?pwd=2ry9"},
            { "全国DEM数据(Alos、哥白尼)", "https://pan.baidu.com/s/1HE65j13W4ub-wSfIw98YTg?pwd=6872"},
            { "全国64个城市建筑数据", "https://pan.baidu.com/s/1K7mwPKSlv52SLKR0FdWnng?pwd=q29q"},
            { "福建省村界(接近三调的精度)", "https://pan.baidu.com/s/1I888_ES174rvZpkrmzJ_5Q?pwd=ey7u"},
        };


        // 软件安装包
        public static Dictionary<string, string> softDict = new Dictionary<string, string>()
        {
            { "ArcGIS Pro3.4.3中文破解版安装教程(内有安装包下载链接)", "https://mp.weixin.qq.com/s/rrYkCLiNsJ2BDrjTiIYkWw?poc_token=HMHyZGijwfUctLONcis4QKBoBAqpqQaSO6yK1vP1"},
            { "AccessDatabaseEngine_X64,X32(Pro中不能正常打开Excel的解决方案)", "https://pan.baidu.com/s/1n5Ar1EMmBbWcnIQt-KMs5w?pwd=6san"},
            { "shape文件修复工具_ShapeChecker", "https://pan.baidu.com/s/1fCHeHgeaA0LcqmEoLVkjcw?pwd=ywej"},
            { "谷谷GIS地图下载器(免费查看、下载)", "https://pan.baidu.com/s/1vjCB8vdu6vrGdXrxj32xCg?pwd=fs8j"},
        };

        #endregion
    }

}
